#include "CmdJsonManager/CmdJsonManager.h"



string CmdJsonManager::jsonFile = "cmds.json";
json CmdJsonManager::cmd_json;
vector<Cmd_Data> CmdJsonManager::cmd_datas;

void to_json(json& j, const Cmd_Data& c)
{
	j["name"] = c.name;
	j["data_f"] = c.data_f;
	j["data"] = c.data;
}

void from_json(const json& j, Cmd_Data& c)
{
	j.at("name").get_to(c.name);
	j.at("data_f").get_to(c.data_f);
	j.at("data").get_to(c.data);
}

vector<Cmd_Data> CmdJsonManager::initAllCmds()
{

	fstream json_ifs(jsonFile, ios::in);
	if (!json_ifs.good()) {
		LoggerSingleton::getInstance().critical("json file dont exist, have create it");
		json_ifs.open(jsonFile, ios::out);
	}
	if (!json_ifs.is_open()) {
		LoggerSingleton::getInstance().critical("json file open fail");
		return vector<Cmd_Data>();
	}
	

	Cmd_Data cmd_data;
	try {
		json_ifs >> cmd_json;
		for (auto tmp : cmd_json) {
			tmp.get_to(cmd_data);
			cmd_datas.push_back(cmd_data);
			cout << cmd_data.name << " " << cmd_data.data_f << " " << cmd_data.data << endl;
		}
	}
	catch (const exception& e) {
		LoggerSingleton::getInstance().critical("json file parse fail:" + string(e.what()));
		return vector<Cmd_Data>();
	}

	return cmd_datas;
}

void CmdJsonManager::addCmd(Cmd_Data& c)
{
	cmd_json.push_back(c);
}

void CmdJsonManager::deleteCmd(Cmd_Data& c)
{
	//for (auto tmp : cmd_json) {
	//	try {
	//		if (tmp.at("name") == c.name && tmp.at("data_f") == c.data_f && tmp.at("data") == c.data) {
	//			cmd_json.erase(tmp);
	//			break;
	//		}
	//	}
	//	catch (exception& e) {
	//		LoggerSingleton::getInstance().critical(string("delete fail:") + e.what());
	//	}
	//}

	for (int i = 0; i < cmd_json.size(); i++) {
		try {
			if (cmd_json.at(i).at("name") == c.name && cmd_json.at(i).at("data_f") == c.data_f && cmd_json.at(i).at("data") == c.data) {
				cmd_json.erase(i);
				break;
			}
		}
		catch (exception& e) {
			LoggerSingleton::getInstance().critical(string("delete fail:") + e.what());
		}
	}
}

void CmdJsonManager::dump()
{
	fstream fs(jsonFile, ios::out);
	fs << setw(4) << cmd_json;
}
